﻿Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Drawing
Imports System.IO.Compression
Imports System.Reflection

Public Class myaccount_Default
    Inherits System.Web.UI.Page
    Protected Sub GetAllUsers()
        DropDownList1.Items.Clear()
        Dim DataTable As MembershipUserCollection = Membership.GetAllUsers()
        Dim Row As MembershipUser
        Dim Odd As Boolean = False
        For Each Row In DataTable
            DropDownList1.Items.Add(Row.UserName)
        Next
        DropDownList1.Items.Add("%%")
    End Sub
    Sub ResetText()
        txtassignedTo.Text = ""
        txtCurrentAssignee.Text = ""
        txtYearAcquired.Text = ""
        txtDatePurchased.Text = ""
        txtSupplier.Text = ""
        txtDateDelivered.Text = ""
        txtAssetno.Text = ""
        txtdevicetype.Text = ""
        txtserial.Text = ""
        txtbrand.Text = ""
        txtmodel.Text = ""
        txtspecss.Text = ""
        txtpo.Text = ""
        txtwarranty.Text = ""
        txtcost.Text = ""
        txtinvoice.Text = ""
        txtrecieved.Text = ""
        txtdaterecieved.Text = ""
        txtdeployedby.Text = ""
        txtdatedeployement.Text = ""
        txtstatus.Text = ""
        txtlanip.Text = ""
        txtgatewayip.Text = ""
        txtos.Text = ""
        txtother1.Text = ""
        txtother2.Text = ""
        txtassignee3.Text = ""
        txtassignee4.Text = ""
    End Sub
    Protected Sub GetTotalRows()
        Dim dv As DataView = SqlSearch.Select(DataSourceSelectArguments.Empty)
        Dim rc As Integer = dv.Count
        lblResultCount.Text = "About " & rc & " results"
    End Sub

    Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Session("SelectedIndex") = -1
        Response.Redirect("default.aspx?search_query=" & txtFind.Text & "&author=" & DropDownList1.SelectedItem.Text)

        'Session("findstring") = "%" & txtFind.Text & "%"
        'Request.QueryString("search_query")
        ' Session("SelectedUserIndex") = DropDownList1.SelectedIndex

        'OnClientClick="return confirm('Are you sure you want to do this');"
    End Sub

    Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
        Session("IdentityName") = DropDownList1.SelectedValue
    End Sub

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
       
    End Sub
    Function DeleteRecord() As Boolean
        Try
            SqlUpdateRecord.Delete()
            Dim delcon = New SqlConnection(ConfigurationManager.ConnectionStrings("Management_Info_SysConnectionString").ConnectionString)
            Dim del = New SqlCommand()
            del.CommandText = "Delete [Management_Info_Sys].[dbo].[img_items] where [img_table] = 'ita_items" & txtAssetno.Text & "'"
            del.Connection = delcon
            delcon.Open()
            del.ExecuteNonQuery()
            delcon.Close()

            Dim isreadonly As PropertyInfo = _
            GetType(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance Or BindingFlags.NonPublic)
            isreadonly.SetValue(Me.Request.QueryString, False, Nothing)
            Me.Request.QueryString.Remove("item")

            Response.Redirect(Request.Url.AbsoluteUri)

            Return True
        Catch ex As Exception
            AppendLog(ex.Message)
            Return False
        End Try
    End Function
    Sub AppendLog(errstring As String)
        Dim err As New CustomValidator
        err.IsValid = False
        err.ErrorMessage = errstring
        Page.Validators.Add(err)
    End Sub
    Protected Sub Page_LoadComplete(sender As Object, e As EventArgs) Handles Me.LoadComplete

        If DropDownList1.Items.Count = 0 Then
            GetAllUsers()
            If Roles.IsUserInRole(Context.User.Identity.Name.ToString(), "Manager") Then
                DropDownList1.Enabled = True
                DropDownList1.SelectedValue = Request.QueryString("author")
            ElseIf Roles.IsUserInRole(Context.User.Identity.Name.ToString(), "Viewer") Then
                DropDownList1.Enabled = True
                Button1.Enabled = False
                DropDownList1.SelectedValue = Request.QueryString("author")
            Else
                DropDownList1.Enabled = False
                DropDownList1.SelectedValue = Context.User.Identity.Name.ToString()
            End If

        End If

        Try
            Dim ImageKey As String = "Default"
            Dim dvSql As DataView = DirectCast(SqlGetInfo.Select(DataSourceSelectArguments.Empty), DataView)
            For Each drvSql As DataRowView In dvSql
                'txtAssetno.Text = drvSql("assetno").ToString()
                'txtserial.Text = drvSql("serialno").ToString()
                ImageKey = "ita_items" & drvSql("assetno").ToString()
            Next

            Image1.ImageUrl = "../imggen.aspx?PictureID=" & ImageKey
            'HyperLink2.ImageUrl = "../imggen.aspx?PictureID=" & ImageKey
            HyperLink2.NavigateUrl = "../imggen.aspx?PictureID=" & ImageKey
            'HyperLink2.ImageUrl = 200

        Catch ex As Exception
            Image1.ImageUrl = "../imggen.aspx?PictureID=Default"
            ' HyperLink2.ImageUrl = "../imggen.aspx?PictureID=Default"
            HyperLink2.NavigateUrl = "../imggen.aspx?PictureID=Default"
            'HyperLink2.Height = 200
        End Try

        txtFind.Text = Request.QueryString("search_query")
        If Request.QueryString("item") = "" Then
            DetailsPanel.Visible = False
        Else
            DetailsPanel.Visible = True
        End If
        SetInfo()

        Try
            GetTotalRows()
        Catch ex As Exception
            AppendLog(ex.Message)
        End Try



        'delete
        If Roles.IsUserInRole(Context.User.Identity.Name.ToString(), "Manager") Or Session("ItemAssetUploadedBy") = Session("AccountName") Then
            Button4.Attributes.Add("OnClick", _
         "return confirm('Are you sure you want to do this');")
        Else
            Button4.Visible = False
        End If



        If Page.IsPostBack = True Then
            If Session("DeleteMethod") = True Then
                'Response.Write("Page.IsPostBack = true")
                If DeleteRecord() = True Then
                    '    'Me.Controls.Clear()
                    '    'DetailsPanel.Controls.Clear()
                    '    Response.Redirect("../myaccount/redirect.aspx")
                    lblLogs.CssClass = "SuccessLogs"
                    lblLogs.Text = "Success"
                    lblLogs.Visible = True
                    '    ResetText()
                    Session("DeleteMethod") = False
                End If
            End If
        End If
    End Sub

    Public Shared Function Compress(bytes As Byte()) As Byte()
        Dim stream = New MemoryStream()
        Dim zipStream = New DeflateStream(stream, CompressionMode.Compress, True)
        zipStream.Write(bytes, 0, bytes.Length)
        zipStream.Close()
        Return stream.ToArray()
    End Function

    Protected Sub GridView2_PageIndexChanged(sender As Object, e As EventArgs) Handles GridView2.PageIndexChanged
        Session("SelectedTabIndex") = GridView2.PageIndex
        Session("SelectedIndex") = -1

        Dim isreadonly As PropertyInfo = _
        GetType(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance Or BindingFlags.NonPublic)
        isreadonly.SetValue(Me.Request.QueryString, False, Nothing)
        Me.Request.QueryString.Remove("item")
        'GridView2.SelectedIndex = -1
    End Sub

    Protected Sub GridView2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView2.SelectedIndexChanged
        'Session("UKey") = GridView2.SelectedRow.Cells(1).Text
        Session("SelectedIndex") = GridView2.SelectedIndex
        'GridView2.SelectedIndex = -1
        Response.Redirect("default.aspx?search_query=" & Request.QueryString("search_query") & "&author=" & Request.QueryString("author") & "&item=" & GridView2.SelectedRow.Cells(1).Text)
    End Sub

    Sub SetInfo()
        Try
            GridView2.SelectedIndex = Integer.Parse(Session("SelectedIndex"))
            GridView2.PageIndex = Integer.Parse(Session("SelectedTabIndex"))
        Catch ex As Exception
            'GridView2.SelectedIndex = -1
        End Try

        Try
            Dim dvSql As DataView = DirectCast(SqlGetInfo.Select(DataSourceSelectArguments.Empty), DataView)
            For Each drvSql As DataRowView In dvSql
                DropDownList2.SelectedValue = drvSql("company").ToString()
                DropDownList3.SelectedValue = drvSql("store").ToString()
                Response.Write(drvSql("store").ToString())
                Try
                    lstAssetClass.SelectedValue = drvSql("assetclass").ToString()
                Catch ex As Exception
                    lstAssetClass.Text = drvSql("assetclass").ToString()
                Finally

                End Try


                txtassignedTo.Text = drvSql("assignedto").ToString()
                txtCurrentAssignee.Text = drvSql("currentassignee").ToString()
                txtYearAcquired.Text = drvSql("yearpurchased").ToString()
                txtDatePurchased.Text = drvSql("datepurchased").ToString()
                txtSupplier.Text = drvSql("supplier").ToString()
                txtDateDelivered.Text = drvSql("datedelivered").ToString()
                txtAssetno.Text = drvSql("assetno").ToString()
                txtdevicetype.Text = drvSql("devicetype").ToString()
                txtserial.Text = drvSql("serialno").ToString()
                txtbrand.Text = drvSql("brand").ToString()
                txtmodel.Text = drvSql("model").ToString()
                txtspecss.Text = drvSql("specs").ToString()
                txtpo.Text = drvSql("po").ToString()
                txtwarranty.Text = drvSql("warranty").ToString()
                txtcost.Text = drvSql("cost").ToString()
                txtinvoice.Text = drvSql("invoiceno").ToString()
                txtrecieved.Text = drvSql("recievedby").ToString()
                txtdaterecieved.Text = drvSql("daterecieved").ToString()
                txtdeployedby.Text = drvSql("deployedby").ToString()
                txtdatedeployement.Text = drvSql("dateofdeployment").ToString()
                txtstatus.Text = drvSql("status").ToString()
                txtlanip.Text = drvSql("lanip").ToString()
                txtgatewayip.Text = drvSql("gatewayip").ToString()
                txtos.Text = drvSql("os_software").ToString()
                txtother1.Text = drvSql("other1").ToString()
                txtother2.Text = drvSql("other2").ToString()

                txtassignee3.Text = drvSql("Assignee3").ToString()
                txtassignee4.Text = drvSql("Assignee4").ToString()
                txtassignee5.Text = drvSql("Assignee5").ToString()

                Session("ItemAssetUploadedBy") = drvSql("UploadedBy").ToString()
            Next
        Catch ex As Exception

        End Try

    End Sub
    Protected Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim exportGridView As New GridView
        Dim sqldatapara As New Parameter
        SqlSearch.SelectParameters("tableslist").DefaultValue = "*"

        exportGridView.DataSource = SqlSearch
        exportGridView.DataBind()


        Response.Clear()
        Response.AddHeader("content-disposition", "attachment; filename=ITAsset" & txtFind.Text & ".xls")
        Response.Charset = ""

        ' If you want the option to open the Excel file without saving than
        'comment out the line below
        ' Response.Cache.SetCacheability(HttpCacheability.NoCache);

        Response.ContentType = "application/vnd.xls"

        Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter
        Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)

        VerifyRenderingInServerForm(exportGridView)

        exportGridView.RenderControl(htmlWrite)

        Response.Write(stringWrite.ToString())

        Response.End()

        SqlSearch.SelectParameters("tableslist").DefaultValue = "ita_key,company,assetno,serialno,assetclass,store,assignedto,supplier,model,status"

    End Sub
    Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)

    End Sub

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            Session("DeleteMethod") = False
            Session("DateNow") = Now.ToString

            SqlUpdateRecord.Update()

            If FileUpload1.HasFile = True Then
                Dim MIMEType As String = Nothing
                Dim extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower()

                Select Case extension
                    Case ".gif"
                        MIMEType = "image/gif"
                    Case ".jpg", ".jpeg", ".jpe"
                        MIMEType = "image/jpeg"
                    Case ".png"
                        MIMEType = "image/png"

                    Case Else
                        'Invalid file type uploaded
                        MIMEType = "Invalid Image"
                        Exit Sub
                End Select

                If MIMEType <> "Invalid Image" Then
                    'Clear Image
                    Dim delcon = New SqlConnection(ConfigurationManager.ConnectionStrings("Management_Info_SysConnectionString").ConnectionString)
                    Dim del = New SqlCommand()
                    del.CommandText = "Delete [Management_Info_Sys].[dbo].[img_items] where [img_table] = 'ita_items" & txtAssetno.Text & "'"
                    del.Connection = delcon
                    delcon.Open()
                    del.ExecuteNonQuery()
                    delcon.Close()
                    'Add
                    Using myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("Management_Info_SysConnectionString").ConnectionString)
                        Const SQL As String = "INSERT INTO [img_items] ([img_table], [img_desc], [img]) VALUES (@img_table, @img_desc, @img)"
                        Dim myCommand As New SqlCommand(SQL, myConnection)
                        'myCommand.Parameters.AddWithValue("@img_desc", FileUpload1.FileName.Trim)
                        myCommand.Parameters.AddWithValue("@img_table", "ita_items" & txtAssetno.Text)
                        myCommand.Parameters.AddWithValue("@img_desc", MIMEType)

                        'Load FileUpload's InputStream into Byte array
                        Dim imageBytes(FileUpload1.PostedFile.InputStream.Length) As Byte
                        FileUpload1.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length)
                        myCommand.Parameters.AddWithValue("@img", Compress(imageBytes))

                        myConnection.Open()
                        myCommand.ExecuteNonQuery()
                        myConnection.Close()
                    End Using
                End If
            End If
            lblLogs.CssClass = "SuccessLogs"
            lblLogs.Text = "Success"
            lblLogs.Visible = True
            ResetText()
        Catch ex As Exception
            AppendLog(ex.Message)
        End Try
    End Sub

    Protected Sub Page_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
        Dim setFocus As String = ""

        setFocus &= "setTimeout(""SetFocus()"", 1000);"

        setFocus &= ""

        setFocus &= "function SetFocus() "

        setFocus &= "{"

        setFocus &= " try{"

        setFocus &= "document.getElementById('" & Me.Button1.ClientID & "').focus();"

        setFocus &= "}catch(er){}"

        setFocus &= "}"

        ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "SetFocus", setFocus, True)
    End Sub

    
    Protected Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Session("DeleteMethod") = True
    End Sub
End Class
